<template>
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card warehouse-card" shadow="hover">
        <div class="stat-icon">
          <el-icon :size="40"><OfficeBuilding /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">仓库数量</div>
          <div class="stat-value">{{ dashboardData.warehouseCount }}</div>
          <div class="stat-trend" :class="{'trend-up': dashboardData.warehouseTrend > 0}">
            <el-icon><CaretTop v-if="dashboardData.warehouseTrend > 0" /><CaretBottom v-else /></el-icon>
            {{ Math.abs(dashboardData.warehouseTrend) }}%
          </div>
        </div>
      </el-card>

      <el-card class="stat-card storage-card" shadow="hover">
        <div class="stat-icon">
          <el-icon :size="40"><Grid /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">库区数量</div>
          <div class="stat-value">{{ dashboardData.storageAreaCount }}</div>
          <div class="stat-trend" :class="{'trend-up': dashboardData.storageAreaTrend > 0}">
            <el-icon><CaretTop v-if="dashboardData.storageAreaTrend > 0" /><CaretBottom v-else /></el-icon>
            {{ Math.abs(dashboardData.storageAreaTrend) }}%
          </div>
        </div>
      </el-card>

      <el-card class="stat-card location-card" shadow="hover">
        <div class="stat-icon">
          <el-icon :size="40"><MapLocation /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">库位数量</div>
          <div class="stat-value">{{ dashboardData.locationCount }}</div>
          <div class="stat-trend" :class="{'trend-up': dashboardData.locationTrend > 0}">
            <el-icon><CaretTop v-if="dashboardData.locationTrend > 0" /><CaretBottom v-else /></el-icon>
            {{ Math.abs(dashboardData.locationTrend) }}%
          </div>
        </div>
      </el-card>
    </div>

    <!-- 折线图区域 -->
    <div class="chart-container">
      <el-card shadow="hover" class="chart-card">
        <template #header>
          <div class="chart-header">
            <span class="chart-title">业务数据趋势</span>
            <div class="chart-actions">
              <el-radio-group v-model="timeRange" size="small" @change="onTimeRangeChange">
                <el-radio-button label="today">今日</el-radio-button>
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
              </el-radio-group>
              <el-button :icon="RefreshRight" size="small" @click="refreshData" :loading="isRefreshing">刷新</el-button>
            </div>
          </div>
        </template>
        <div ref="chartRef" class="chart" style="width: 100%; height: 500px;"></div>
      </el-card>
    </div>

    <!-- 连接状态指示器 -->
    <div class="connection-status" :class="{'connected': isConnected, 'disconnected': !isConnected}">
      <el-icon><Connection v-if="isConnected" /><Remove v-else /></el-icon>
      <span>{{ isConnected ? 'SignalR已连接' : 'SignalR未连接' }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance, nextTick } from 'vue';
import * as signalR from '@microsoft/signalr';
import * as echarts from 'echarts';
import { 
  OfficeBuilding, Grid, MapLocation, CaretTop, CaretBottom, 
  RefreshRight, Connection, Remove 
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance();

// SignalR连接
let connection = null;
let chart = null;

// 响应式数据
const chartRef = ref(null);
const isConnected = ref(false);
const isRefreshing = ref(false);
const timeRange = ref('today');

// 大屏数据
const dashboardData = reactive({
  warehouseCount: 0,
  warehouseTrend: 0,
  storageAreaCount: 0,
  storageAreaTrend: 0,
  locationCount: 0,
  locationTrend: 0,
  chartData: {
    times: [],
    orderData: [],
    shipmentData: [],
    outboundData: []
  }
});

/**
 * 初始化图表
 */
const initChart = () => {
  if (!chartRef.value) return;
  
  chart = echarts.init(chartRef.value);
  
  const option = {
    title: {
      text: '订单、发货、出库数量趋势',
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['订单数量', '发货数量', '出库数量'],
      top: 40,
      textStyle: {
        fontSize: 14
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '100px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dashboardData.chartData.times,
      axisLabel: {
        fontSize: 12,
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 12,
        color: '#666'
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#e0e0e0'
        }
      }
    },
    series: [
      {
        name: '订单数量',
        type: 'line',
        smooth: true,
        data: dashboardData.chartData.orderData,
        lineStyle: {
          width: 3,
          color: '#5470c6'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
            { offset: 1, color: 'rgba(84, 112, 198, 0.05)' }
          ])
        },
        itemStyle: {
          color: '#5470c6'
        }
      },
      {
        name: '发货数量',
        type: 'line',
        smooth: true,
        data: dashboardData.chartData.shipmentData,
        lineStyle: {
          width: 3,
          color: '#91cc75'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(145, 204, 117, 0.3)' },
            { offset: 1, color: 'rgba(145, 204, 117, 0.05)' }
          ])
        },
        itemStyle: {
          color: '#91cc75'
        }
      },
      {
        name: '出库数量',
        type: 'line',
        smooth: true,
        data: dashboardData.chartData.outboundData,
        lineStyle: {
          width: 3,
          color: '#fac858'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(250, 200, 88, 0.3)' },
            { offset: 1, color: 'rgba(250, 200, 88, 0.05)' }
          ])
        },
        itemStyle: {
          color: '#fac858'
        }
      }
    ]
  };
  
  chart.setOption(option);
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart && chart.resize();
  });
};

/**
 * 更新图表数据
 */
const updateChart = () => {
  if (!chart) return;
  
  chart.setOption({
    xAxis: {
      data: dashboardData.chartData.times
    },
    series: [
      { data: dashboardData.chartData.orderData },
      { data: dashboardData.chartData.shipmentData },
      { data: dashboardData.chartData.outboundData }
    ]
  });
};

/**
 * 加载大屏数据
 */
const loadDashboardData = async () => {
  try {
    console.log('📊 开始加载大屏数据...');
    
    const response = await proxy.http.post('/api/Dashboard/GetDashboardData', {
      timeRange: timeRange.value
    });
    
    if (response && response.status) {
      const data = response.data;
      
      // 更新卡片数据
      dashboardData.warehouseCount = data.warehouseCount || 0;
      dashboardData.warehouseTrend = data.warehouseTrend || 0;
      dashboardData.storageAreaCount = data.storageAreaCount || 0;
      dashboardData.storageAreaTrend = data.storageAreaTrend || 0;
      dashboardData.locationCount = data.locationCount || 0;
      dashboardData.locationTrend = data.locationTrend || 0;
      
      // 更新图表数据
      dashboardData.chartData.times = data.chartData?.times || [];
      dashboardData.chartData.orderData = data.chartData?.orderData || [];
      dashboardData.chartData.shipmentData = data.chartData?.shipmentData || [];
      dashboardData.chartData.outboundData = data.chartData?.outboundData || [];
      
      // 更新图表
      updateChart();
      
      console.log('✅ 大屏数据加载成功');
    } else {
      console.error('❌ 加载大屏数据失败:', response?.message);
    }
  } catch (error) {
    console.error('❌ 加载大屏数据异常:', error);
  }
};

/**
 * 刷新数据
 */
const refreshData = async () => {
  isRefreshing.value = true;
  await loadDashboardData();
  isRefreshing.value = false;
  ElMessage.success('数据已刷新');
};

/**
 * 时间范围变化
 */
const onTimeRangeChange = async () => {
  await loadDashboardData();
};

/**
 * 初始化SignalR连接
 */
const initSignalR = async () => {
  try {
    console.log('🚀 正在初始化SignalR连接...');
    
    const apiBaseUrl = window.ipAddress || 'http://localhost:9991/';
    const signalRUrl = apiBaseUrl + 'api/signalr/DashboardHub';
    
    console.log('📡 SignalR连接地址:', signalRUrl);
    
    connection = new signalR.HubConnectionBuilder()
      .withUrl(signalRUrl, {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
      })
      .withAutomaticReconnect([0, 1000, 3000, 5000, 10000])
      .configureLogging(signalR.LogLevel.Information)
      .build();

    // 监听数据更新事件
    connection.on('ReceiveDashboardUpdate', (data) => {
      console.log('📡 收到大屏数据更新:', data);
      
      // 更新卡片数据
      if (data.warehouseCount !== undefined) dashboardData.warehouseCount = data.warehouseCount;
      if (data.storageAreaCount !== undefined) dashboardData.storageAreaCount = data.storageAreaCount;
      if (data.locationCount !== undefined) dashboardData.locationCount = data.locationCount;
      
      // 更新图表数据
      if (data.chartData) {
        Object.assign(dashboardData.chartData, data.chartData);
        updateChart();
      }
    });

    // 连接关闭事件
    connection.onclose((error) => {
      console.log('❌ SignalR连接已断开', error);
      isConnected.value = false;
    });

    // 重连中事件
    connection.onreconnecting((error) => {
      console.log('🔄 SignalR正在重连...', error);
      isConnected.value = false;
    });

    // 重连成功事件
    connection.onreconnected((connectionId) => {
      console.log('✅ SignalR已重新连接, ConnectionId:', connectionId);
      isConnected.value = true;
      connection.invoke('JoinGroup', 'Dashboard').catch(err => {
        console.error('❌ 重新加入大屏数据组失败:', err);
      });
      // 重新加载数据
      loadDashboardData();
    });

    // 启动连接
    await connection.start();
    console.log('✅ SignalR连接成功, ConnectionId:', connection.connectionId);
    isConnected.value = true;
    
    // 加入大屏数据组
    await connection.invoke('JoinGroup', 'Dashboard');
    console.log('✅ 已加入大屏数据实时更新组');
    
    // 通知服务器启动定时推送
    try {
      await proxy.http.post('/api/Dashboard/StartAutoPush');
      console.log('✅ 已启动服务器端定时推送');
    } catch (error) {
      console.warn('⚠️ 启动定时推送失败:', error.message);
    }
    
  } catch (error) {
    console.error('❌ SignalR连接失败:', error);
    isConnected.value = false;
    ElMessage.warning('实时连接失败，将使用手动刷新模式');
  }
};

/**
 * 组件挂载
 */
onMounted(async () => {
  console.log('📊 实时大屏页面初始化...');
  
  // 等待DOM渲染
  await nextTick();
  
  // 初始化图表
  initChart();
  
  // 加载数据
  await loadDashboardData();
  
  // 初始化SignalR
  await initSignalR();
});

/**
 * 组件卸载
 */
onUnmounted(async () => {
  console.log('🔚 实时大屏页面卸载...');
  
  // 销毁图表
  if (chart) {
    chart.dispose();
    chart = null;
  }
  
  // 停止服务器端定时推送
  try {
    await proxy.http.post('/api/Dashboard/StopAutoPush');
    console.log('✅ 已停止服务器端定时推送');
  } catch (error) {
    console.warn('⚠️ 停止定时推送失败:', error.message);
  }
  
  // 断开SignalR连接
  if (connection) {
    try {
      await connection.invoke('LeaveGroup', 'Dashboard');
      await connection.stop();
      console.log('✅ SignalR连接已断开');
    } catch (error) {
      console.error('❌ 断开SignalR连接失败:', error);
    }
  }
});
</script>

<style scoped lang="less">
.dashboard-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
  
  // 统计卡片区域
  .stat-cards {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    margin-bottom: 20px;
    
    .stat-card {
      cursor: pointer;
      transition: all 0.3s ease;
      border-radius: 12px;
      overflow: hidden;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
      }
      
      :deep(.el-card__body) {
        display: flex;
        align-items: center;
        padding: 30px;
      }
      
      .stat-icon {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20px;
        color: #fff;
      }
      
      .stat-content {
        flex: 1;
        
        .stat-label {
          font-size: 14px;
          color: #999;
          margin-bottom: 8px;
        }
        
        .stat-value {
          font-size: 32px;
          font-weight: bold;
          color: #333;
          margin-bottom: 8px;
          font-family: 'Arial', sans-serif;
        }
        
        .stat-trend {
          font-size: 14px;
          color: #67c23a;
          display: flex;
          align-items: center;
          gap: 4px;
          
          &.trend-up {
            color: #67c23a;
          }
          
          &:not(.trend-up) {
            color: #f56c6c;
          }
        }
      }
      
      &.warehouse-card .stat-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }
      
      &.storage-card .stat-icon {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }
      
      &.location-card .stat-icon {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }
    }
  }
  
  // 图表容器
  .chart-container {
    .chart-card {
      border-radius: 12px;
      
      .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .chart-title {
          font-size: 18px;
          font-weight: bold;
          color: #333;
        }
        
        .chart-actions {
          display: flex;
          gap: 12px;
          align-items: center;
        }
      }
      
      .chart {
        margin-top: 20px;
      }
    }
  }
  
  // 连接状态指示器
  .connection-status {
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 6px;
    z-index: 1000;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
    transition: all 0.3s ease;
    
    &.connected {
      background: #67c23a;
      color: #fff;
    }
    
    &.disconnected {
      background: #f56c6c;
      color: #fff;
    }
  }
}

// 响应式布局
@media (max-width: 1200px) {
  .stat-cards {
    grid-template-columns: repeat(2, 1fr) !important;
  }
}

@media (max-width: 768px) {
  .stat-cards {
    grid-template-columns: 1fr !important;
  }
}
</style>
